import React, { Suspense } from "react";
import { Navigate, useLocation } from "react-router-dom";
import usePermission from "../hooks/usePermission";
import { RouteConfig } from "./types";

interface AuthGuardProps {
  route: RouteConfig;
  children: React.ReactNode;
  fallback?: React.ReactNode;
}

/**
 * 授权守卫组件，用于控制路由访问权限
 */
const AuthGuard: React.FC<AuthGuardProps> = ({
  route,
  children,
  fallback = <div>加载中...</div>,
}) => {
  const permission = usePermission();
  const location = useLocation();

  // 检查是否需要认证
  if (route.meta?.requiresAuth && !permission.isAuthenticated()) {
    return <Navigate to="/login" replace state={{ from: location.pathname }} />;
  }

  // 检查是否有访问权限
  if (!permission.canAccess(route)) {
    return <Navigate to="/unauthorized" replace />;
  }

  // 如果有重定向，执行重定向
  if (route.redirect) {
    return <Navigate to={route.redirect} replace />;
  }

  // 使用 Suspense 包装子组件
  return <Suspense fallback={fallback}>{children}</Suspense>;
};

export default AuthGuard;
